﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using System.Globalization;
using WCF;
using System.Web.Security;
using System.Data;

namespace geekmeet
{
    /// <summary>
    /// The page that handles the private messages between users
    /// </summary>
    public partial class Messages : System.Web.UI.Page
    {
        GeekMeetService wcf = new GeekMeetService();
        protected Guid loggedInUserGUID = (Guid)Membership.GetUser().ProviderUserKey;
        Guid conversationUser;

        protected void Page_Load(object sender, EventArgs e)
        {
            CheckPremium();
            EditSitemap();

            if (Request.QueryString["action"] == ("ViewConversation"))
            {
                try
                {
                    // Who is the conversation with
                    conversationUser = Guid.Parse(Request.QueryString["user"]);
                    ShowConversation(loggedInUserGUID, conversationUser);
                    HighlightContact();
                }
                catch
                {
                    // "User" querystring is not valid
                    // so display error message
                    Response.Redirect("/Error404.aspx");
                }
            }
        }

        private void EditSitemap()
        {
            // Show sitemap in format username > page
            SiteMap.CurrentNode.ParentNode.ReadOnly = false;
            SiteMap.CurrentNode.ParentNode.Title = Membership.GetUser().UserName;
            SiteMap.CurrentNode.ParentNode.Url = "Profile.aspx?user=" + loggedInUserGUID.ToString();
        }

        /// <summary>
        /// Gets the friends that the user has had a conversation with
        /// </summary>
        private void GetContacts()
        {
            List<FriendComposite> contactList = new List<FriendComposite>();
            contactList = wcf.GetConversationContacts(loggedInUserGUID);

            ContactRepeater.DataSource = contactList;
            ContactRepeater.DataBind();
        }

        /// <summary>
        /// Checks if user is premium and can view messages
        /// </summary>
        private void CheckPremium()
        {
            // Decide if user can view messages
            bool IsPremium = Roles.IsUserInRole("premiumuser");

            if (IsPremium)
            {
                multiViewPageContent.SetActiveView(viewPremium);
                GetContacts();
                //ShowConversation(loggedInUserGUID,conversationUser);
            }
            else
                multiViewPageContent.SetActiveView(viewUpgrade);
        }

        /// <summary>
        /// Shows the conversation between 2 users
        /// </summary>
        private void ShowConversation(Guid user1, Guid user2)
        {
                //Get messages
                List<MessageComposite> conversation = wcf.GetConversation(loggedInUserGUID, conversationUser);

                messageRepeater.DataSource = conversation;
                messageRepeater.DataBind();
                panSendQuickMessage.Visible = true;

                wcf.SetMessagesIsRead(conversationUser,loggedInUserGUID);

        }

        /// <summary>
        /// Highlights selected contact
        /// </summary>
        private void HighlightContact()
        {
            // Highlight selected contact after page load
            // using javascript function in geekmeet.js
            Page.ClientScript.RegisterStartupScript(
            this.GetType(), "highlightContact", "highlightContact('"
                + conversationUser + "');", true);
        }


        /// <summary>
        /// Fires when a user presses send message button
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSendMessage_Click(object sender, EventArgs e)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                SendNewMessage();
            }
         
        }

        /// <summary>
        /// Sends the message
        /// </summary>
        private void SendNewMessage()
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                Guid recipientID;
                string message = messagestxtMessage.Text;
                string recipientName = messagestxtRecipient.Text;
                try
                {
                    recipientID = Guid.Parse(hiddenUserID.Value);
                    wcf.SendMessage(loggedInUserGUID, recipientID, message);

                    Page.ClientScript.RegisterStartupScript(
                   this.GetType(), "showNotificationMessage", "showNotificationMessage('Meddelandet har skickats till " + recipientName + "' );", true);

                    GetContacts();
                    Response.Redirect("Messages.aspx?action=ViewConversation&user=" + recipientID);
                }
                catch
                {
                    Page.ClientScript.RegisterStartupScript(
                  this.GetType(), "showNotificationMessage", "showNotificationMessage('Användaren " + recipientName + " finns inte.' );", true);
                }
            }
        }

        protected void btnQuickSend_Click(object sender, EventArgs e)
        {
            SendQuickMessage();
        }

        private void SendQuickMessage()
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                string message = txtMessage.Text;
                wcf.SendMessage(loggedInUserGUID, conversationUser, message);
                Response.Redirect("Messages.aspx?action=ViewConversation&user=" + conversationUser);

            }
            else
                Response.Redirect("/Default.aspx");
        }
    }
}